package com.seveneight.baijiesteward.ui.main.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseActivity;
import com.seveneight.baijiesteward.base.Message;
import com.seveneight.baijiesteward.base.MessageEvent;
import com.seveneight.baijiesteward.base.SDKConfig;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.bean.UserConfigBean;
import com.seveneight.baijiesteward.bean.VersionBean;
import com.seveneight.baijiesteward.ui.first.contract.VersionUpdateContract;
import com.seveneight.baijiesteward.ui.first.presenter.VersionUpdatePresenter;
import com.seveneight.baijiesteward.ui.main.contract.LoginContract;
import com.seveneight.baijiesteward.ui.main.contract.UserConfigContract;
import com.seveneight.baijiesteward.ui.main.fragment.MainFragment;
import com.seveneight.baijiesteward.ui.main.presenter.LoginPresenter;
import com.seveneight.baijiesteward.ui.main.presenter.UserConfigPresenter;
import com.seveneight.baijiesteward.utils.ACache;
import com.seveneight.baijiesteward.utils.AppUtil;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.PreferencesUtil;
import com.seveneight.baijiesteward.utils.Setting;
import com.seveneight.baijiesteward.utils.StringUtils;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.views.UpdateDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, UserConfigContract.UserConfigView, LoginContract.LoginView, VersionUpdateContract.VersionUpdateView {

    VersionUpdateContract.VersionUpdatePresenter versionUpdatePresenter;
    LoginContract.LoginPresenter loginPresenter;
    private static final int REQUEST__PERMISSIONS = 1;
    UserConfigContract.UserConfigPresenter userConfigPresenter;
    private UpdateDialog updateDialog;

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void initView() {
        setSwipeBackEnable(false);
        if (findFragment(MainFragment.class) == null) {
            loadRootFragment(R.id.layout_content, MainFragment.newInstance());
        }
    }

    @Override
    protected void initData() {
        initAccessTokenWithAkSk();
        loginPresenter = new LoginPresenter(this);
        userConfigPresenter = new UserConfigPresenter(this);
        versionUpdatePresenter = new VersionUpdatePresenter(this);
        versionUpdatePresenter.getVersionInfo();
        if (setting.isLogin()) {
            if (StringUtils.isEmpty(Setting.getInstance(getContext()).getUserID()) && StringUtils.isEmpty(PreferencesUtil.get(getContext(),PreferencesUtil.userId,""))){
                setting.setIsLogin(false);
                EventBus.getDefault().post(new MessageEvent(Message.CHECK_OUT));
            }else {
                loginPresenter.getUserInfo("正在获取个人信息...", activity, jsonFormat.commonParam());
            }
        }
    }

    @Override
    protected void setListener() {

    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }


    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //初始化百度识别
    private void initAccessTokenWithAkSk() {
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                LogUtil.d("识别功能初始化成功");
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDialog("识别功能初始化失败，请联系客服");
                    }
                });
            }
        }, activity, SDKConfig.BAIDU_API_KEY, SDKConfig.BAIDU_SECRET_KEY);
    }

    @Override
    protected void onStart() {
        super.onStart();
        retuqstReadPermissions();
    }

    @AfterPermissionGranted(REQUEST__PERMISSIONS)
    private void retuqstReadPermissions() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "应用需要申请部分手机权限", REQUEST__PERMISSIONS, perms);
        }
    }

    @Override
    public void rebackConfig(List<UserConfigBean> data) {

    }

    @Override
    public void reBackkUser(UserBean bean) {

    }

    @Override
    public void backUserInfo(UserBean bean) {
        setting.setUserInfo(bean);
        EventBus.getDefault().post(new MessageEvent(1));
    }

    @Override
    public void rebackVersionInfo(VersionBean versionBean) {
        setting.setVersion(versionBean);
        if (updateDialog == null) {
            updateDialog = new UpdateDialog(activity);
        }
        if (versionBean.getVersionCode() > AppUtil.getselfVersionCode(activity)) {
            if (!PreferencesUtil.get(activity,versionBean.getVersionName(),"0").equals("1"))
                updateDialog.needUpdateDialog(versionBean);
            PreferencesUtil.put(activity,versionBean.getVersionName(),"1");
        }
//        if (versionBean.getVersionCode() > AppUtil.getselfVersionCode(activity)) {
//            updateDialog.needUpdateDialog(versionBean);
//        }
    }
}
